package com.netty.option;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author xl-9527
 * @since 2025/8/11
 **/
public class OptionDemo {

    public ChannelFuture optionClientRun() throws InterruptedException {
        final Bootstrap bootstrap = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 500)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(final NioSocketChannel ch) throws Exception {
                        final ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new ChannelInboundHandlerAdapter() {

                                    @Override
                                    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                                        ctx.writeAndFlush(ctx.alloc().buffer().writeBytes("Hello World".getBytes(StandardCharsets.UTF_8)));
                                        super.channelActive(ctx);
                                    }
                                });
                    }
                });
        return bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080)).sync();
    }
}
